package com.zhangyj.util;

import javax.servlet.http.HttpServletRequest;

import com.zhangyj.db.DBUtil;

public class Pagination {
	public static final String ATTRIBUTE_ID = "pagnation";
	public static final String PAGE_NAME = "page";
	private static final int DEFAULT_PAGE_SIZE = 20;

	private int pageSize = DEFAULT_PAGE_SIZE; // 每页的记录数
	private int start = 0; // 当前页第一条数据在List中的位置,从0开始
	private int page = 1; // 当前页
	private int totalPage = 0; // 总计有多少页
	private int totalCount = 0; // 总记录数
	private String url;

	// 构造函数
	public Pagination() {
	}

	public Pagination(int page) {
		this.page = page;
	}

	public Pagination(HttpServletRequest request) {
		this.page = Tools.str2int(request.getParameter("page"), 1);
		request.setAttribute(Pagination.ATTRIBUTE_ID, this);
	}

	public void setPage(int page) {
		if (page > 0) {
			start = (page - 1) * pageSize;
			this.page = page;
		}
	}

	public int getPage() {
		return page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public Pagination setPageSize(int pageSize) {
		this.pageSize = pageSize <= 0 ? DEFAULT_PAGE_SIZE : pageSize;
		return this;
	}

	public int getStart() {
		return start;
	}

	/**
	 * @return the totalCount
	 */
	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
		totalPage = (int) Math.ceil((totalCount + pageSize - 1) / pageSize);
		start = (page - 1) * pageSize;
	}

	public int getTotalPage() {
		return totalPage;
	}

	/**
	 * 获取上一页页数
	 * 
	 * @return
	 */
	public int getPrePage() {
		if (hasPrePage()) {
			return page - 1;
		}
		return page;
	}

	public int getNextPage() {
		if (hasNextPage()) {
			return page + 1;
		}
		return page;
	}

	/**
	 * 该页是否有下一页.
	 */
	public boolean hasNextPage() {
		return page < totalPage;
	}

	/**
	 * 该页是否有上一页.
	 */
	public boolean hasPrePage() {
		return page > 1;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String builderSql(String sql, String orderField, String orderTable, boolean isDesc) {
		return DBUtil.buildPagnationSql(sql, page, pageSize, totalCount, orderField, orderTable, isDesc);
	}
}